<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 支付回调
// +----------------------------------------------------------------------
namespace app\ymkj\controller;

use app\model\Order as orderModel;
use think\facade\Log;
use think\Db;

class WxNotify
{
  public function handle()
  {
    //接收微信返回的数据数据,返回的xml格式
    $xmlData = isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
    //将xml格式转换为数组
    $data = $this->FromXml($xmlData);
    $arr = array();
    //为了防止假数据，验证签名是否和返回的一样。
    //记录一下，返回回来的签名，生成签名的时候，必须剔除sign字段。
    $sign = $data['sign'];
    unset($data['sign']);
    if($sign == $this->getSign($data))
    {
      $this->NotifyProcess($data);
    }
    else
    {
      Log::error($data['return_msg']);
    }
  }

  // 根据返回的订单号做业务逻辑
  private function NotifyProcess($data)
  {
    if($data['result_code'] == 'SUCCESS' && $data['return_code']=="SUCCESS") {
      $orderNo = $data['out_trade_no'];
      Db::startTrans();
      try {
        $order = orderModel::where('id','=',$orderNo)->lock(true)->find();
        // 检测支付状态为未支付
        if($order->status == 0) {
          $this->updateOrderStatus($order->id);
          if ($order->type == 'more') {
            $start_time = time();
            $end_time = time()+365*24*60*60;
            $this->fenxiao($order->jine,$order->openid);
            $result = Db::name('user')
              ->where('openid','=',$order->openid)
              ->update(['vip'=>1,'bolishui'=>12,'start_time' =>$start_time,'end_time'=>$end_time]);
          }
        }
        Db::commit();
        return true;
      }
      catch(Exception $ex) {
        Db::rollback();
        Log::error($ex);
        return false;
      }
    }
    else {
      return true;
    }
  }

  // 更新支付状态
  private function updateOrderStatus($orderID)
  {
    orderModel::where('id','=',$orderID)->update(['status'=>1]);
  }

  // 分销
  public function fenxiao($jine,$user)
  {
    $fenxiao = Db::name('fenxiao')->where('fenxiao','=','fenxiao')->find();
    $wxuser = Db::name('user')->where('openid','=',$user['openid'])->find();
    if($fenxiao['status'] == 1 && $fenxiao['type'] == 1){ // 百分比分销
      $f1 = Db::name('user')->where('openid','=',$wxuser['f1'])->setInc('balance',round($jine*$fenxiao['f1']/100,2));
      $f2 = Db::name('user')->where('openid','=',$wxuser['f2'])->setInc('balance',round($jine*$fenxiao['f2']/100,2));
      $f3 = Db::name('user')->where('openid','=',$wxuser['f3'])->setInc('balance',round($jine*$fenxiao['f3']/100,2));
    }
    if($fenxiao['status'] == 1 && $fenxiao['type'] == 2){ // 固定金额
      $f1 = Db::name('user')->where('openid','=',$wxuser['f1'])->setInc('balance',$fenxiao['f1']);
      $f2 = Db::name('user')->where('openid','=',$wxuser['f2'])->setInc('balance',$fenxiao['f2']);
      $f3 = Db::name('user')->where('openid','=',$wxuser['f3'])->setInc('balance',$fenxiao['f3']);
    }
  }

  // 将xml格式转换为数组
  private function FromXml($xml)
  {
    if (empty($xml)) {
      # 如果没有数据，直接返回失败
      return false;
    }
    //将XML转为array
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $data;
  }

  // 生成签名
  public function getSign($params) 
  {
    ksort($params);   //将参数数组按照参数名ASCII码从小到大排序
    foreach ($params as $key => $item) {
      if (!empty($item)) {         //剔除参数值为空的参数
        $newArr[] = $key.'='.$item;     // 整合新的参数数组
      }
    }
    $stringA = implode("&", $newArr);         //使用 & 符号连接参数
    $stringSignTemp = $stringA."&key="."jhsa415DSF45AS5asd485sa4521JHBhg";  // key是在商户平台API安全里自己设置的
    $stringSignTemp = MD5($stringSignTemp);       //将字符串进行MD5加密
    $sign = strtoupper($stringSignTemp);      //将所有字符转换为大写
    return $sign;
  }
}
?>